package datastruct.algorithm;

public class BackPack01 {

    public static void main(String[] args) {

        int[] weight = {2,3,4,5};
        int[] value = {3,4,5,6};
        System.out.println(maxValue(weight,value,8));
    }

    public static int maxValue(int[] weights, int[] values, int capacity){
        int n = weights.length;
        int[][] dp = new int[n+1][capacity+1]; //dp[i][j]代表容量为j的背包装前i个物品能获得的最大价值
        //dp第一行表示前0个物品，即一个物品也不装， 第一列表示容量为0的背包，这两地方默认就是0
        for (int i = 1; i <=n ; i++) { //前i-1个物品
            for (int j = 1; j <=capacity ; j++) { //从容量为1开始
                //第k个物品装还是不装
                int k = i-1;
                //1.装不下
                if(j<weights[k]) dp[i][j] = dp[k][j];
                //2.装得下，但有装和不装两种选择
                else {
                    int add = dp[i - 1][Math.max(0, j - weights[k])] + values[k];
                    int notAdd = dp[i - 1][j];
                    dp[i][j] = Math.max(add, notAdd);
                }
            }
        }
        return dp[n][capacity];
    }
}
